//
//  ParticularsViewController.m
//  MyLearnJob
//
//  Created by qianfeng on 15-6-28.
//  Copyright (c) 2015年 朱共营. All rights reserved.
//

#import "ParticularsViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "AFNetworking.h"
#import "MessageMode.h"
#import "MessageCell.h"
#import "ChapterModel.h"
#import "ChapterCell.h"
#import "NoteModel.h"
#import "NoteCell.h"
#import "VedioView.h"
#import "UMSocial.h"


@interface ParticularsViewController ()<UITableViewDataSource,UITableViewDelegate,UMSocialUIDelegate>
{
   
    UITableView *_tableView;
    NSMutableArray *_dataArr;
    AFHTTPRequestOperationManager *_manager;
    NSString *_str;
    UITableView *_MytableView;
    
    BOOL _isFirst;
    BOOL _isNote;
    NSString *_myStr;
    
    NSString *_WhichOnePlay;
    BOOL _canPlay;
    NSString *_newID;
    NSMutableArray *_firstData;
    NSMutableArray *_twoData;
    NSMutableArray *_thredData;
    
    BOOL _isLoad;

    UIButton *_button;
    BOOL _btnPlay;
    ChapterModel *_setModel;
    
    
}
@property(nonatomic) VedioView *playerView;
@property(nonatomic) UISlider *slider;
@property(nonatomic) AVPlayer *player;


@property(nonatomic,strong) NSMutableArray *firstData;
@property(nonatomic,strong) NSMutableArray *twoData;
@property(nonatomic,strong) NSMutableArray *thredData;
@property(nonatomic,strong)  UITableView *MytableView;
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) NSMutableArray *dataArr;
@property(nonatomic,strong) ChapterModel *setModel;
@end

@implementation ParticularsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     [self creatSlideView];
    self.automaticallyAdjustsScrollViewInsets=NO;
    self.slider.maximumValue=1.0;
    self.slider.minimumValue=0.0;
    self.slider.value=0.0;
    self.automaticallyAdjustsScrollViewInsets=NO;
    self.dataArr=[[NSMutableArray alloc] init];
    self.firstData=[[NSMutableArray alloc] init];
    self.twoData=[[NSMutableArray alloc] init];
    self.thredData=[[NSMutableArray alloc] init];
    self.tableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenSize.width, kScreenSize.height) style:UITableViewStylePlain];
    self.MytableView=[[UITableView alloc] initWithFrame:CGRectMake(0, kScreenSize.height*2/7+40+64, kScreenSize.width, kScreenSize.height-kScreenSize.height*2/7-40-64)];
    _manager=[AFHTTPRequestOperationManager manager];
    _manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    [self creatBartItem];
   [self downLoadWithURL:kSecendURLMain];
    _isFirst=YES;
    _isNote=NO;
    [self firstDown];
   
}
- (void)firstDown{
    
    [self creatSubSeting];
    [self NumberThred];

}
- (void)creatBartItem{
    
    
    UIBarButtonItem *iten=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"full_back_btn"] style:UIBarButtonItemStylePlain target:self action:@selector(backHome:)];
   
    
//    
//    UIBarButtonItem *down=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ic_down_downing@3x"] style:UIBarButtonItemStylePlain target:self action:@selector(backHome:)];
//    
//   
//    
//    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
//    UIImage *image2 = [UIImage imageNamed:@"btn_showmoocfollow@3x"];
//    button2.frame = CGRectMake(0, 0, image2.size.width, image2.size.height);
//    [button2 setImageEdgeInsets:UIEdgeInsetsMake(0, 15, 0, -15)];
//    [button2 setImage:image2 forState:UIControlStateNormal];
//    button2.tag=103;
//    [button2 addTarget:self action:@selector(backHome:) forControlEvents:UIControlEventTouchUpInside];
//    button2.titleLabel.font = [UIFont systemFontOfSize:16];
//    
//    UIBarButtonItem *loa=[[UIBarButtonItem alloc] initWithCustomView:button2];
//    
    
//    UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
//    UIImage *image3 = [UIImage imageNamed: @"btn_showmoocshare_hl"];
//    button3.frame = CGRectMake(0, 0, image3.size.width, image3.size.height);
//    [button3 setImageEdgeInsets:UIEdgeInsetsMake(0, 15, 0, -15)];
//    [button3 setImage:image3 forState:UIControlStateNormal];
//    button3.tag=104;
//    [button3 addTarget:self action:@selector(backHome:) forControlEvents:UIControlEventTouchUpInside];
//    button3.titleLabel.font = [UIFont systemFontOfSize:16];
//
    
    UIBarButtonItem *shar=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed: @"btn_showmoocshare_hl"] style:UIBarButtonItemStylePlain target:self action:@selector(sharIt:)];
  
    self.navigationItem.leftBarButtonItem=iten;
    self.navigationItem.rightBarButtonItem=shar;
}
- (void)sharIt:(UIBarButtonItem *)bat{
    
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"507fcab25270157b37000010"
                                      shareText:@"你要分享的文字"
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToQzone,UMShareToEmail,UMShareToWechatSession,nil]
                                       delegate:self];
}
- (void)backHome:(UIBarButtonItem *)bat{
                [self.player pause];
          
           // [[NSNotificationCenter defaultCenter] removeObserver:self name:@"status" object:nil];
            [self.navigationController popViewControllerAnimated:YES];
           // [self dismissViewControllerAnimated:YES completion:nil];
    
}
- (BOOL)isDirectShareInIconActionSheet{
    return YES;
}
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response{
    if (response.responseCode==UMSResponseCodeSuccess) {
        NSLog(@"112");
    }

}

- (void)creatSlideView{
     _button=[UIButton buttonWithType:UIButtonTypeSystem];
    _button.frame=CGRectMake(10, kScreenSize.height*2/7+40-10, 30, 30);
    [_button setImage:[UIImage imageNamed: @"full_play_btn"] forState:UIControlStateNormal];
    [_button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
   
    self.slider=[[UISlider alloc] initWithFrame:CGRectMake(40, kScreenSize.height*2/7+40, kScreenSize.width-80, 15)];
    [self.slider addTarget:self action:@selector(sliderClick:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_button];
    [self.view addSubview:self.slider];

}
- (void)btnClick:(UIButton *)btn{
    if (_btnPlay) {
        [_button setImage:[UIImage imageNamed: @"full_play_btn"] forState:UIControlStateNormal];
        [self.view addSubview:_button];
        [self.player play];
        _btnPlay=NO;
       // [self.navigationController setNavigationBarHidden:NO];
    }else{
    [_button setImage:[UIImage imageNamed: @"full_pause_btn"   ] forState:UIControlStateNormal];
    [self.player pause];
    
    [self.view addSubview:_button];
        _btnPlay=YES;
       // [self.navigationController setNavigationBarHidden:YES];
    }
}
- (void)sliderClick:(UISlider *)sende{
    float progressValue=self.slider.value;
    CMTime totalTime=self.player.currentItem.duration;
    [self.player seekToTime:CMTimeMultiplyByFloat64(totalTime, progressValue)];
    
}


#pragma mark - 创建播放视图
- (void)creatPlayView{
//    if (self.player!=nil) {
//        [self.player play];
//        return;
//    }
     self.automaticallyAdjustsScrollViewInsets=NO;
       
    self.playerView=[[VedioView alloc] initWithFrame:CGRectMake(5,0, kScreenSize.width-10, kScreenSize.height*2/7+20)];
    self. playerView.backgroundColor=[UIColor redColor];
    if (_canPlay) {
        
        [self.player pause];
        AVURLAsset *assert=[[AVURLAsset alloc] initWithURL:[NSURL URLWithString:_WhichOnePlay] options:nil];
        AVPlayerItem *item=[[AVPlayerItem alloc] initWithAsset:assert];
        [self.view addSubview:self.playerView];
        self.player=[AVPlayer playerWithPlayerItem:item];
        [self.playerView setPlayer:self.player];
[item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionOld context:nil];
        
    }else{
        
       
        AVURLAsset *assert=[[AVURLAsset alloc] initWithURL:[NSURL URLWithString:_str] options:nil];
        AVPlayerItem *item=[[AVPlayerItem alloc] initWithAsset:assert];
      
        [self.view addSubview:self.playerView];
        self.player=[AVPlayer playerWithPlayerItem:item];
        [self.playerView setPlayer:self.player];
        //[item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    }
 
  
    [self.player play];
 
    [self.tableView reloadData];
   
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItem *item=(AVPlayerItem *)object;
        if (item.status==AVPlayerItemStatusReadyToPlay) {
            [self.player play];
            
            __weak typeof(self)weakSelf=self;
            [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
                CMTime totalTime=weakSelf.player.currentItem.duration;
                CGFloat currentTimeSeconds=CMTimeGetSeconds(time);
                CGFloat totalSeconds=CMTimeGetSeconds(totalTime);
                weakSelf.slider.value=currentTimeSeconds*1.0/totalSeconds;
            }];
        }else{
            NSLog(@"影片不能播放");
        
        }
    }

}
#pragma mark - 分栏控制器
- (void)creatSubSeting{
    
   
    
    NSArray *arr=@[@"详细信息",@"相关推荐",@"章节"];
    UISegmentedControl *seg=[[UISegmentedControl alloc] initWithItems:arr];
    seg.frame=CGRectMake(0, kScreenSize.height*2/7+64, kScreenSize.width, 40);
    seg.selectedSegmentIndex=2;
    [seg addTarget:self action:@selector(segClick:) forControlEvents:UIControlEventValueChanged];
    
    [self.view addSubview:seg];


}
- (void)segClick:(UISegmentedControl *)seg{
    switch (seg.selectedSegmentIndex) {
        case 0://详细信息
        {NSLog(@"0");
 
                [self.firstData removeLastObject];
                 _isNote=NO;
            _isFirst=NO;
            [self NumberOne];
            [self.MytableView reloadData];
            
        }
            break;
        case 1://相关推荐
        {
             NSLog(@"1");
            [self.twoData removeAllObjects];
            _isFirst=NO;
            _isNote=YES;
            [self NumberTwo];
            [self.MytableView reloadData];
        }
            break;
        case 2://章节
        {
             NSLog(@"2");
            [self.dataArr removeAllObjects];
            _isFirst=YES;
            _isNote=NO;
            [self NumberThred];
            [self.MytableView reloadData];
        }
            break;
            
        default:
            break;
    }


}
#pragma mark - 视频详细信息下载
- (void)NumberOne{
    [self.MytableView registerNib:[UINib nibWithNibName:@"MessageCell" bundle:nil] forCellReuseIdentifier:@"MessageCell"];
    [self MymessageDownloadWithUrl:kSecendURLXX];
  
    [self creatAddView];
}
- (void)MymessageDownloadWithUrl:(NSString *)url{
    __weak typeof(self)weakSelf=self;
    NSDictionary *dict=@{@"uid":@(0),@"cid":weakSelf.idd,@"token":@"5f5786aad68fcc240eb2a5e0deaf9f5b"};
    [_manager POST:url parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"详情信息下载成功");
                
        
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSArray *data=dic[@"data"];
        for (NSDictionary *sub in data) {
            MessageMode *model=[[MessageMode alloc] init];
            [model setValuesForKeysWithDictionary:sub];
            NSArray *list=sub[@"teacher_list"];
            
           // NSMutableArray *mutArr=[[NSMutableArray alloc] init];
            for (NSDictionary *myList in list) {
                model.nickname=myList[@"nickname"];
                model.aboutme=myList[@"aboutme"];
                model.pic=myList[@"pic"];
             
               // [mutArr addObject:model];
                
              
            }
            NSLog(@"%@",model.nickname);
            
           
            [weakSelf.firstData addObject:model];
        }
        
        [weakSelf.MytableView reloadData];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"详情信息下载失败");
    }];


}
#pragma mark - 评论下载
- (void)NumberTwo{
    [self.MytableView registerNib:[UINib nibWithNibName:@"NoteCell" bundle:nil] forCellReuseIdentifier:@"NoteCell"];
    [self DownLoadNoteWithURL:kNoteURL];
    [self creatAddView];
    
    
}
- (void)DownLoadNoteWithURL:(NSString *)url{
    __weak typeof(self)MySelf=self;
   //  NSString *str=[NSString stringWithFormat:@"%ld",_myStr.integerValue];
    
     NSString *str=[[NSString alloc] init];
    if (_canPlay) {
        str =[NSString stringWithString:_newID];
    }else{
        str=[NSString stringWithString:_myStr];
    }
    NSLog(@"%@",str);
   
    
    NSDictionary *dict=@{@"uid":@"2092964",@"page":@(1),@"mid":str,@"token":@"d189d5d9119f5676dd3c1127f2ab50cc"};
    //NSLog(@"%@",dict);
    [_manager POST:url parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"评论下成功");
       
        
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dic[@"errorCode"]);
        if ([dic[@"errorCode"] isEqual:@(1005)]) {
          
//           UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(0, kScreenSize.height*2/5+40, kScreenSize.width, kScreenSize.height-kScreenSize.height*2/5-40)];
//            imageView.image=[UIImage imageNamed: @"ic_note_blankpage"] ;
//            [MySelf.view addSubview:imageView];
            UIView *view=[[UIView alloc] init];
            view.backgroundColor=[UIColor clearColor];
            [self.MytableView setTableHeaderView:view];
            
            
            return ;
        }else{
        NSArray *data=dic[@"data"];
        for (NSDictionary *sub in data) {
            NoteModel *model=[[NoteModel alloc] init];
            NSDictionary *user=sub[@"user"];
            model.uid=user[@"uid"];
            
            model.sex=user[@"sex"];
            
            model.pic=user[@"pic"];
         //  NSLog(@"%@",model.pic);
            model.nickname=user[@"nickname"];
            
            model.is_v=user[@"is_v"];
  
            NSDictionary *note=sub[@"note"];
            
            model.id=note[@"id"];
            
            model.desc=note[@"desc"];
            
            model.praise_num=note[@"praise_num"];
            
            model.collect_num=note[@"collect_num"];
            
            model.course_id=note[@"course_id"];
            
            model.course_name=note[@"course_name"];
            
            model.chapter_num=note[@"chapter_num"];
            
            model.section_num=note[@"section_num"];
            
            model.is_praise=note[@"is_praise"];
            
            model.is_collect=note[@"is_collect"];
            
            model.last_date=note[@"last_date"];
            
            model.last_time=note[@"last_time"];
            
            model.create_date=note[@"create_date"];
            
            model.from=note[@"from"];
            
            
            [MySelf.dataArr addObject:model];
            [MySelf.twoData addObject:model];
          //  NSLog(@"%@",model.pic);
        }
        [MySelf.MytableView reloadData];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"评论下载失败");
    }];

}
#pragma mark - 章节下载
- (void)NumberThred{
    [self.dataArr removeAllObjects];
    [self.MytableView registerNib:[UINib nibWithNibName:@"ChapterCell" bundle:nil] forCellReuseIdentifier:@"ChapterCell"];
    [self myChapterCellWithURL:kSecendURLZJ];
    
    [self creatAddView];
    

}
- (void)myChapterCellWithURL:(NSString *)url{
    __weak typeof(self)weakSelf=self;
    NSDictionary *dict=@{@"uid":@(0),@"cid":self.idd,@"token":@"8a23e151eacfe1e9556e71f8eb6b3c9b"};
[_manager POST:url parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
   
    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
    NSArray *data=dic[@"data"];
    for (NSDictionary *sub in data) {
        
        NSArray *media=sub[@"media"];
        NSDictionary *chap=sub[@"chapter"];
        
        NSLog(@"%@",chap[@"name"]);
        for (NSDictionary *mysub in media) {
            ChapterModel *model=[[ChapterModel alloc] init];
             NSLog(@"%@",mysub[@"name"]);
           
            [model setValuesForKeysWithDictionary:mysub];
            [weakSelf.dataArr addObject:model];
        }
     
    }
    [weakSelf.MytableView reloadData];
    
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    
}];
}
- (void)creatAddView{
    self.MytableView.delegate=self;
    self.MytableView.dataSource=self;
    
    [self.view addSubview:self.MytableView];

}
#pragma mark - 跳转第一次播放
- (void)downLoadWithURL:(NSString *)url{
    __weak typeof(self)weakSelf=self;
    NSString *str=[NSString stringWithFormat:@"%@",self.idd];
    NSDictionary *dict=@{@"uid":@(0),@"cid":str,@"token":@"9bb4b17710b70a920a1a121cba84c1c2"};
    
    [_manager POST:url parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"视频数据下载OK");
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *data=dic[@"data"];
        NSDictionary *media=data[@"media"];
       _str=[[NSString alloc] initWithString:media[@"media_url"]];
        _myStr =[[NSString alloc] initWithFormat:@"%@",media[@"id"] ];
      //  NSLog(@"%@",_myStr);
       
       [weakSelf creatPlayView];
       
        [weakSelf.tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"视频播放失败");
    }];

}
#pragma mark - tableView协议
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_isNote) {
        return self.twoData.count;
    }
    if (_isFirst) {
        return self.dataArr.count;
    }else{
        
    return self.firstData.count;
    }
    
    
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   // NSLog(@"%d",_isFirst);
  //  NSLog(@"%@",self.dataArr);
    if (_isNote) {
        NoteCell *cell=[self.MytableView dequeueReusableCellWithIdentifier:@"NoteCell" forIndexPath:indexPath];
        NoteModel *model=self.twoData[indexPath.row];
        [cell showDataWithModel:model];
        return cell;
    }
    if (_isFirst) {
        
        
        ChapterModel *model=self.dataArr[indexPath.row];
        ChapterCell *cell=[self.MytableView dequeueReusableCellWithIdentifier:@"ChapterCell" forIndexPath:indexPath];
        
        [cell showDataWithModel:model];
        
        return cell;
        
    }
    else{
        MessageMode *model=self.firstData[indexPath.row];
        MessageCell *cell=[self.MytableView dequeueReusableCellWithIdentifier:@"MessageCell" forIndexPath:indexPath];
        [cell showDataWithModel:model];
        
        return cell;
    
    
    }
}
#pragma mark - 选中行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_isNote) {
        
        NSLog(@"信息");
        return;
        
    }if (_isFirst) {
        ChapterModel *model=self.dataArr[indexPath.row];
        _WhichOnePlay =[[NSString alloc] initWithFormat:@"%@",model.media_url];
        NSLog(@"%@",model.id);
        NSLog(@"%@",model.media_url);
        NSLog(@"%@",_WhichOnePlay);
        _newID=[NSString stringWithFormat:@"%ld",model.id.integerValue];
        NSLog(@"%@",_newID);
        _canPlay=YES;
        self.setModel=model;
        
       
        [self creatPlayView];
        
        
        
    }else{
        NSLog(@"详情");
        
        
    
    
    }





}
#pragma mark -  设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_isNote) {
        return 125;
    }
    if (_isFirst) {
        NSLog(@"523");
        return 52;
    }else{
     NSLog(@"52");
    return 523;

    }
   }
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
